package com.sdp.wx.controller;


import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.wx.cache.clean.WxCleanCache;
import com.sdp.wx.db.wx_warehouse_info.entity.WxWarehouseInfo;
import com.sdp.wx.db.wx_warehouse_info.service.IWxWarehouseInfoService;
import com.sdp.wx.utils.WxConstants;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/WxWarehouseInfoController")
public class WxWarehouseInfoController {

	@Autowired
	private IWxWarehouseInfoService iWxWarehouseInfoService;
	
	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private WxCleanCache wxCleanCache;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iWxWarehouseInfoService, WxWarehouseInfo.class, dataCenter));
	}
	
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody WxWarehouseInfo warehouseInfo) {
		if(warehouseInfo==null) {
			return Result.error("仓库信息为空");
		}
		if(StringUtils.isEmpty(warehouseInfo.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iWxWarehouseInfoService, WxWarehouseInfo.class, new String[] {"warehouseCode","warehouseName"}, "keyId", warehouseInfo, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("仓库编号和名称不能重复");
			}
			warehouseInfo.setIsUse(WxConstants.是.getCode());
			warehouseInfo.setIsLock(WxConstants.否.getCode());
			warehouseInfo.setCreateTime(LocalDateTime.now());
			iWxWarehouseInfoService.save(warehouseInfo);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iWxWarehouseInfoService, WxWarehouseInfo.class, new String[] {"warehouseCode","warehouseName"}, "keyId", null, warehouseInfo, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("仓库编号和名称不能重复");
			}
			
			iWxWarehouseInfoService.updateById(warehouseInfo);
		}
		wxCleanCache.cleanWarehouseCache();
		return Result.ok();
	}
	
}

